class InterceptorManager {
  handler = [];
  use(fulfilled, rejected) {
    this.handler.push({fulfilled, rejected});
  }

  forEach(cb) {
    this.handler.forEach(interceptor => {
      cb(interceptor);
    });
  }
}

const axios = {
  interceptor: {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  }
};

axios.request = function (config, dispatch) {
  const chain = [dispatch, undefined];
  let promise = Promise.resolve(config);

  this.interceptor.request.forEach(interceptor => {
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });

  this.interceptor.response.forEach(interceptor => {
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });

  console.log([...chain]);
  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }

  console.log(promise);
  return promise;
};

function dispatch(config) {
  console.log('发送请求的最终配置为：' + JSON.stringify(config));
  // return Promise.resolve(config);
  return Promise.reject({mag: '请求发生错误'});
}

axios.interceptor.request.use(config => {
  config.request1 = 'request1';
  console.log('请求拦截成功，在config中添加属性request1');
  return config;
});

axios.interceptor.request.use(config => {
  config.request2 = 'request2';
  console.log('请求拦截成功，在config中添加属性request2');
  return config;
});

axios.interceptor.response.use(
  response => {
    response.response1 = 'response1';
    console.log('响应拦截成功，在response中添加属性response1');
    // return response;
    return Promise.reject('err');
  },
  reason => Promise.reject(reason)
);
axios.interceptor.response.use(
  response => {
    response.response2 = 'response2';
    console.log('响应拦截成功，在response中添加属性request2');
    return response;
  },
  reason => Promise.reject(reason)
);

axios
  .request({rowData: 'row'}, dispatch)
  .then(response => {
    console.log(response);
  })
  .catch(err => {
    console.log(err);
  });
